package com.example.it.looker.view.customview;

/**
 * Created by 鲁迅认识的那只猹 on 9/1/2017 3:06 PM.
 * Emial 1258730808@qq.com
 * Desc:
 */

import android.content.Context;
import android.util.AttributeSet;
import android.view.View;
import android.widget.AbsListView;
import android.widget.ListView;

import com.example.it.looker.R;

/**
 * 支持上滑加载更多的ListView
 */
public class MyListView extends ListView implements AbsListView.OnScrollListener {


    /**
     * 想ListView的最后添加元素
     */
    public interface OnAppendElement {
        void appendElement();
    }


    private View footerView;

    private int currentIndex;

    private int totalItem;

    private OnAppendElement onAppendElement;

    public MyListView(Context context) {
        super(context);
        init();
    }

    public MyListView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    private void init() {
        this.footerView = View.inflate(this.getContext(), R.layout.footer, null);
        this.footerView.setVisibility(GONE);
        setOnScrollListener(this);
    }

    /**
     * 当ListView的滑动状态改变的时候触发的事件
     */
    @Override
    public void onScrollStateChanged(AbsListView view, int scrollState) {
        //当ListView已经滑动到最后，并且是闲置状态
        if (currentIndex == totalItem && scrollState == SCROLL_STATE_IDLE) {
            this.footerView.setVisibility(VISIBLE);
            if (this.onAppendElement != null) {
                this.onAppendElement.appendElement();
            }

        }
    }

    /**
     * 当ListView滑动的时候触发的事件
     */
    @Override
    public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
        this.currentIndex = firstVisibleItem + visibleItemCount;
        this.totalItem = totalItemCount;
    }

    /**
     * 设置加载更多的事件
     */
    public void setOnAppendElement(OnAppendElement appendElement) {
        this.onAppendElement = appendElement;
    }
}
